#pragma once

#include "SpinLock.h"

template <typename CLock = CFakeLock>
class CBufChunkMgr
{
public:
    CBufChunkMgr() { m_nCur = 0; }
    ~CBufChunkMgr() {}

    void *operator new(size_t, void *ptr) _GLIBCXX_USE_NOEXCEPT { return ptr; }
    void operator delete(void *ptr) {}

public:
    void Init(void *pBuf, uint64_t nLen)
    {
        m_pBuf = pBuf;
        m_nLen = nLen;
    }

    void Destroy() {}

    // 待修改，考虑内存对齐
    void *Alloc(int iLen)
    {
        void *ptr = nullptr;

        if (0 >= iLen)
        {
            printf("CShmBlock::Alloc param error, iLen=%d\n", iLen);
            return nullptr;
        }

        m_lock.lock();

        if (m_nCur + iLen > m_nLen)
        {
            m_lock.unlock();
            printf("CShmBlock::Alloc param error, (m_nCur + iLen > m_nLen)\n");
            return nullptr;
        }

        ptr = (char *)m_pBuf + m_nCur;
        m_nCur += iLen;
        m_lock.unlock();

        return ptr;
    }

    void Free(void *ptr) {}

private:
    void *m_pBuf;
    uint64_t m_nLen;
    uint64_t m_nCur;
    CLock m_lock;
};

// #include "LinkedList.h"

// struct BufChunk
// {
//     unsigned int nLength;
//     void *pStart;
//     void *pEnd;
//     void *pCurPos;
// };

// typedef CLinkedList<BufChunk, CSpinLock> CBufChunkList;
// typedef CBufChunkList::Node BufChunkNode;

// class CBufChunkMgr
// {
// public:
//     CBufChunkMgr();
//     ~CBufChunkMgr();
//     void *operator new(size_t sz);
//     void operator delete(void *ptr);
//     void Destroy();

//     void *Alloc(unsigned int nLen);

// private:
//     BufChunkNode *NewChunk();
//     void DeleteChunk(BufChunkNode *pNode);

//     BufChunkNode *AddNewChunk();

// private:
//     CBufChunkList m_lstChunk;
// };
